<template class="">
  <div class="root-container" v-loading="isLoading">
    <div class="form-container">
      <div class="image-container">
        <SectorImage :seatData="seatStatus" />
      </div>
      <div style="width: 60%; max-width: 700px">
        <el-form label-width="120px">
          <el-form-item label="当前时段">
            <b>{{
              `${currentMoment.format("HH:mm")} ~ ${currentMoment
                .add(1, "hour")
                .format("HH:mm")}`
            }}</b>
          </el-form-item>
          <el-form-item label="扇区数量">
            <b>{{
              `当前 ${currentSectorCount} 扇区  /  计算建议 ${autoAdvice} 扇区`
            }}</b>
          </el-form-item>
          <el-form-item label="人工扇区建议">
            <el-slider
              v-model="formData.sectorAdvice"
              :min="1"
              :max="9"
              show-input
              show-stops
            />
          </el-form-item>
          <el-form-item label="双流机场正常率">
            <el-slider v-model="formData.rateZUUU" show-input />
          </el-form-item>
          <el-form-item label="天府机场正常率">
            <el-slider v-model="formData.rateZUTF" show-input />
          </el-form-item>
          <!-- <el-form-item>
            <p style="font-size: 12px">*机场正常率数据查询NTFM</p>
          </el-form-item> -->
          <el-form-item label="补充信息(选填)">
            <el-input
              v-model="formData.freeText"
              type="textarea"
              clearable
              :autosize="{ minRows: 3, maxRows: 6 }"
              resize="none"
              placeholder="请填写例如空军转场、特情等可能影响运行正常或扇区策略的信息。"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handlePost()">提交记录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- Charts -->
    <el-scrollbar>
      <div class="chart-container">
        <div
          v-for="(airportData, airportDataIndex) in arrangedData"
          class="chart-wrapper"
        >
          <div class="chart-header">
            <el-tag size="small" :type="airportDataIndex < 2 ? 'success' : ''"
              >时段&nbsp;<b
                >{{ dayjs(airportData.timestamp).format("HH:mm") }}~{{
                  dayjs(airportData.timestamp).add(1, "hour").format("HH:mm")
                }}</b
              ></el-tag
            >
            <el-tag size="small" :type="airportDataIndex < 2 ? 'success' : ''"
              >扇区建议&nbsp;<b>{{ airportData.sectorRequire }}扇</b></el-tag
            >
            <el-tag size="small" :type="airportDataIndex < 2 ? 'success' : ''"
              >总架次&nbsp;<b>{{ airportData.total }}</b></el-tag
            >
          </div>
          <AirportChart :airportData="airportData" :showHeader="false" />
          <!-- style="transform: scale(0.92) translateY(-20px)" -->
          <PointChart :airportData="airportData" :showHeader="false" />
          <!-- style="transform: scale(0.92) translateY(-60px)" -->
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>
<script setup>
import { ref, computed, h, onMounted } from "vue";
import dayjs from "dayjs";
import axios from "axios";
import { ElNotification, ElMessageBox } from "element-plus";
import useFlowStore from "@/store/flow.js";
import useSeatStore from "@/store/seat.js";
import * as flowUtils from "@/views/FlowStatus/utils/index.js";
import PointChart from "@/views/FlowStatus/AdvancedChart/PointChart.vue";
import AirportChart from "@/views/FlowStatus/AdvancedChart/AirportChart.vue";
import SectorImage from "@/views/HourStatus/SectorHistory/historyView/sectorImage.vue";

const isLoading = ref(false);

const formData = ref({
  sectorAdvice: 1,
  rateZUUU: 100,
  rateZUTF: 100,
  freeText: "",
});

const currentMoment = computed(() =>
  dayjs()
    .minute(dayjs().minute() > 30 ? 30 : 0)
    .second(0)
);

const seatStore = useSeatStore();

const seatStatus = computed(() => seatStore.seatStatus);

const flowStore = useFlowStore();
// const loaderType = computed(() => flowStore.loaderType);
// const rawData = computed(() => flowStore.rawData);
// const begTime = computed(() => flowStore.begTime);
// const tags = computed(() => flowStore.tags);
// const rawDataLite = computed(() => flowStore.rawData.slice(0, 16));

const autoAdvice = computed(() =>
  Math.max(
    arrangedData.value[0].sectorRequire,
    arrangedData.value[1].sectorRequire
  )
);

const currentSector = computed(() =>
  seatStatus.value.filter((d) => d.sectorCodes.length > 0)
);

const currentSectorCount = computed(() => currentSector.value.length);

const arrangedData = computed(() => {
  const traditionalConfig = {
    dataStep: 4,
    dataInterval: 2,
  };
  // let rawData = flowStore.rawData;
  let rawData = flowStore.rawData.slice(
    0,
    Math.min(flowStore.rawData.length, 40)
  );
  if (!rawData || rawData.length == 0) return [];
  let t0 = dayjs();
  return flowUtils
    .policyCompute(
      flowUtils.arrange(
        flowUtils.cumulate(
          rawData,
          traditionalConfig.dataInterval,
          traditionalConfig.dataStep
        ),
        flowStore.tags,
        flowStore.begTime,
        traditionalConfig.dataInterval,
        ["airport", "type", "point"]
      ),
      traditionalConfig.dataStep
    )
    .filter((airportData) => {
      let t1 = dayjs(airportData.timestamp);
      let diff = t1.diff(t0, "minutes");
      return diff > -60;
      // if (t1.hour() + 1 >= t0.hour() || t1.unix() + 1800 >= t0.unix()) {
      //   if (t1.hour() == t0.hour() && t0.minute() > 30) {
      //     if (t1.minute() >= 30) {
      //       return true;
      //     } else {
      //       return false;
      //     }
      //   } else {
      //     return true;
      //   }
      // } else {
      //   return false;
      // }
    })
    .slice(0, 6);
});

const resetData = () => {
  formData.value.sectorAdvice = seatStatus.value.filter(
    (d) => d.sectorCodes.length > 0
  ).length;
  formData.value.rateZUUU = 98;
  formData.value.rateZUTF = 98;
  formData.value.freeText = "";
};

onMounted(() => {
  resetData();
});

const getPostData = () => {
  return {
    moment: currentMoment.value.format("YYYY-MM-DD HH:mm:ss"),
    timestamp: currentMoment.value.valueOf(),
    flowData: arrangedData.value,
    currentSectorCount: currentSectorCount.value,
    currentSector: currentSector.value,
    autoAdvice: autoAdvice.value,
    manualAdvice: formData.value.sectorAdvice,
    manualDifference: formData.value.sectorAdvice - currentSectorCount.value,
    adviceDifference: autoAdvice.value - currentSectorCount.value,
    rateZUUU: formData.value.rateZUUU,
    rateZUTF: formData.value.rateZUTF,
    freeText: formData.value.freeText,
    updated: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  };
};

const getConfirmMessage = (data) => {
  const rateAlertValue = journalStore.flowNote.rateAlertValue;
  let styles = {
    msg: "font-size:12px;opacity:0.8;",
    div: "display:flex;justify-content:space-between;padding:4px 0;border-top:1px dashed #8884;",
    p: "padding-bottom:12px;",
    pre: "width:100%;height:100px;overflow:auto;padding:4px;border:1px dashed #8884;",
    alert: "color:red;font-weight:bold;",
  };
  return h("div", null, [
    h("p", { style: styles.p }, "该数据提交后不可修改，确认数据填写正确吗？"),
    h("div", { style: styles.msg }, [
      h("div", { style: styles.div }, [
        h("span", null, "记录对应时刻"),
        h("span", null, data.moment),
      ]),
      h("div", { style: styles.div }, [
        h("span", null, "当前扇区数量"),
        h("span", null, data.currentSectorCount),
      ]),
      h("div", { style: styles.div }, [
        h("span", null, "计算建议扇区数量"),
        h("span", null, data.autoAdvice),
      ]),
      h("div", { style: styles.div }, [
        h("span", null, "人工建议扇区数量"),
        h("span", null, data.manualAdvice),
      ]),
      h("div", { style: styles.div }, [
        h("span", null, "人工建议扇区调整"),
        h(
          "span",
          null,
          (data.manualDifference > 0 ? "+" : "") + data.manualDifference
        ),
      ]),
      h("div", { style: styles.div }, [
        h("span", null, "计算建议扇区调整"),
        h(
          "span",
          null,
          (data.adviceDifference > 0 ? "+" : "") + data.adviceDifference
        ),
      ]),
      h("div", { style: styles.div }, [
        h("span", null, "双流机场正常率（人工摘录）"),
        h("span", null, data.rateZUUU + "%"),
      ]),
      h("div", { style: styles.div }, [
        h("span", null, "天府机场正常率（人工摘录）"),
        h("span", null, data.rateZUTF + "%"),
      ]),
      data.rateZUUU < rateAlertValue || data.rateZUTF < rateAlertValue
        ? h("div", { style: styles.div + styles.alert }, [
            // h("span", null, "***"),
            h(
              "span",
              null,
              `机场正常率低于 ${rateAlertValue}% 请立即通知值班主任`
            ),
            // h("span", null, "***"),
          ])
        : null,
      h("div", { style: styles.fiv }, [
        h("span", null, "补充信息"),
        h("span", null, data.freeText),
      ]),
      h("div", { style: styles.div }, [
        h("span", null, "填写时间"),
        h("span", null, data.updated),
      ]),
      h("div", { style: styles.div }, [
        h("span", null, "4小时内流量信息记录"),
        h(
          "span",
          null,
          `${(JSON.stringify(data.flowData).length / 1000).toFixed(2)}kb`
        ),
      ]),
      // h("div", { style: styles.pre }, [
      //   h("pre", null, JSON.stringify(data.flowData, null, 2)),
      // ]),
      h("div", { style: styles.div }, [
        h("span", null, "当前扇区详情记录"),
        h(
          "span",
          null,
          `${(JSON.stringify(data.currentSector).length / 1000).toFixed(2)}kb`
        ),
      ]),
      // h("div", { style: styles.pre }, [
      //   h("pre", null, JSON.stringify(data.currentSector, null, 2)),
      // ]),
    ]),
  ]);
};

const handlePost = () => {
  let data = getPostData();
  let message = getConfirmMessage(data);
  console.log("FlowNote", data);
  ElMessageBox.confirm(message, "数据确认", {
    confirmButtonText: "提交",
    cancelButtonText: "取消",
    // type: "warning",
    draggable: true,
    closeOnClickModal: false,
    closeOnPressEscape: false,
    showClose: false,
  })
    .then(() => {
      //
      isLoading.value = true;
      axios
        .post("api/note_flow_post.php", data)
        .then((response) => {
          console.log(response.data);
          if (response.data.success) {
            ElNotification({
              title: "已提交",
              // message: "记录编号：" + response.data.index + "#",
              type: "success",
            });
            resetData();
          } else {
            ElNotification({
              title: "出错了",
              type: "warning",
            });
          }
          isLoading.value = false;
        })
        .catch((error) => {
          console.error(error);
          ElNotification({
            title: "出错了",
            message: error.message,
            type: "error",
          });
          isLoading.value = false;
        });
    })
    .catch(() => {
      //
    });
};
</script>

<style scoped>
.root-container {
  padding: 24px 0;
}
.form-container {
  width: 100%;
  display: flex;
  /* justify-content: space-between; */
  border-bottom: 1px dashed #8884;
  padding-bottom: 24px;
}
.image-container {
  width: 40%;
  min-width: 500px;
  max-width: 600px;
  padding-right: 24px;
  margin-right: 24px;
  border-right: 1px dashed #8884;
}
.chart-container {
  display: flex;
  /* margin-top: 24px; */
}
.chart-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  transform: scale(0.92) translateX(-60px);
  border-left: 1px dashed #8884;
  padding-left: 40px;
}

.chart-header {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-header > *:not(:last-child) {
  margin-right: 6px;
}
</style>
